import { Component, OnInit, Injector, ViewChild, ElementRef } from '@angular/core';

import { loadModules } from 'esri-loader';
import esri = __esri;
import { AppComponentBase } from '@shared/common/app-component-base';
import { AppConsts } from "@shared/AppConsts";
import { ServiceProxy, ElectronicLockMessageDTO, DispatchDTO } from '@shared/service-proxy/service-proxies';

@Component({
  selector: 'app-lock-address-modal',
  templateUrl: './lock-address-modal.component.html',
  styleUrls: ['./lock-address-modal.component.less']
})
export class LockAddressModalComponent extends AppComponentBase implements OnInit {

  @ViewChild('mapViewNode') private mapViewEl: ElementRef;
  isVisible: boolean = false;
  lockPoint: ElectronicLockMessageDTO;
  lat: number;
  lng: number;
  electronicMessage: ElectronicLockMessageDTO;
  dispatch: DispatchDTO;
  constructor(injector: Injector,
    private _service: ServiceProxy) {
    super(injector);
  }

  ngOnInit() {
  }

  async initializeMap() {
    try {
      const [
        Map,
        MapView,
        ScaleBar,
        TileLayer,
        Graphic] = await loadModules([
          'esri/Map',
          'esri/views/MapView',
          'esri/widgets/ScaleBar',
          'esri/layers/TileLayer',
          "esri/Graphic",
          'dojo/domReady!'
        ], {
            url: AppConsts.arcgisMapUrl, css: AppConsts.arcgisStyleUrl
          });

      // Set type of map
      const map: esri.Map = new Map({
        // basemap: this._basemap,
        layers: new TileLayer({
          url: AppConsts.arcgisMapServerUrl
        })
      });

      const mapView: esri.MapView = new MapView({
        container: this.mapViewEl.nativeElement,
        center: this._center,
        zoom: this._zoom,
        map: map
      });

      // All resources in the MapView and the map have loaded.
      // Now execute additional processes
      mapView.when(() => {
        const scaleBar = new ScaleBar({
          view: mapView,
          unit: "dual" // The scale bar displays both metric and non-metric units.
        });
        mapView.ui.add(scaleBar, "bottom-left");

        // First create a point geometry (this is the location of the Titanic)
        let point = {
          type: "point", // autocasts as new Point()
          longitude: this.lng,
          latitude: this.lat
        };

        // Create a symbol for drawing the point
        let markerSymbol = {
          type: "picture-marker",  // autocasts as new PictureMarkerSymbol()
          url: "/assets/images/icon-location.png",
          width: "25px",
          height: "25px"
        };

        var msg = ""

        if (this.electronicMessage.lockStickStatus) {
          msg += this.l('warn_lever_shearing') + "-";
        }
        if (this.electronicMessage.lockStickStatus) {
          msg += this.l('warn_lever_shearing') + "-";
        }
        if (this.electronicMessage.volt < 3450) {
          msg += this.l('warn_lvd') + "-"
        }
        if (this.electronicMessage.outerStatus) {
          msg += this.l('warn_disassemble_bonnet') + "-"
        }
        if (this.electronicMessage.gpsStatus) {
          msg += this.l('warn_gps_lost') + "-"
        }
        if (this.electronicMessage.isLocked) {
          msg += this.l('lockset_lock_success') + "-";
        }
        else {
          msg += this.l('lockset_unlock_success') + "-";
        }
        msg += this.l('lvd_value') + this.electronicMessage.volt + this.l('millivolt');
        if (!this.dispatch) {
          this.dispatch = new DispatchDTO();
        }
        let lineAtt = {
          containerCode: this.dispatch.containerCode,
          lockCode: this.dispatch.lockCode,
          containerStatusName: msg,
          routeCode: this.dispatch.routeCode,
          launchsiteName: this.dispatch.launchsiteName,
          destinationsiteName: this.dispatch.destinationsiteName,
          platenumber: this.dispatch.platenumber,
          longitude: this.electronicMessage.longitude,
          latitude: this.electronicMessage.latitude,
          time: this.electronicMessage.time,
          speed: this.electronicMessage.speed,
        };
        // Create a graphic and add the geometry and symbol to it
        let pointGraphic = new Graphic({
          geometry: point,
          symbol: markerSymbol,
          attributes: lineAtt,
          popupTemplate: { // autocasts as new PopupTemplate()
            title: "{containerCode}",
            content: [{
              type: "fields",
              fieldInfos: [{
                fieldName: "containerCode",
                label: this.l("container_no")
              }, {
                fieldName: "lockCode",
                label: this.l("lockset_no")
              }, {
                fieldName: "containerStatusName",
                label: this.l("lockset_state")
              }, {
                fieldName: "routeCode",
                label: this.l("path_no")
              }, {
                fieldName: "launchsiteName",
                label: this.l("start_site")
              }, {
                fieldName: "destinationsiteName",
                label: this.l("end_site")
              }, {
                fieldName: "platenumber",
                label: this.l("car_no")
              }, {
                fieldName: "longitude",
                label: this.l("longitude")
              }, {
                fieldName: "latitude",
                label: this.l("latitude")
              }, {
                fieldName: "time",
                label: this.l("get_date")
              }, {
                fieldName: "speed",
                label: this.l("speed")
              }]
            }]
          }
        });


        // Add the graphics to the view's graphics layer
        mapView.graphics.add(pointGraphic);
      });


    } catch (error) {
      console.log('We have an error: ' + error);
    }

  }

  show(lockNo: string): void {

    this._service.getLastAddressByLockNoUsingGET(lockNo).subscribe(result => {

      if (parseInt(result.result.longitude) != 0 && parseInt(result.result.latitude) != 0) {

        this._center = [result.result.longitude, result.result.latitude];
        this.electronicMessage = result.result;

        this.lat = result.result.latitude;
        this.lng = result.result.longitude;

        this.isVisible = true;
        if (this.electronicMessage.dispatchId) {
          this._service.searchDispatchByLockNoUsingGET(lockNo).subscribe(result => {
            this.dispatch = result.result;
            this.initializeMap();
          })
        } else {
          this.initializeMap();
        }
      }
      else {
        this.notification.error(this.l('warn_notification'), this.l("warn_gps_lost"));
      }

    })
  }

  close() {
    this.isVisible = false;
  }
}
